using UnityEngine;

using System.Collections;

public class Dof : PostEffectsBase
{
    private Camera cam;

    public Shader dofShader;
    private Material dofMaterial = null;
    public Material material{
        get {
            dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial);
            return dofMaterial;
        }
    }

    [Range(0,10)]
    public int iterations = 3;

    [Range(1, 8)]
    public int downSample = 2;

    [Range(0, 1)]
    public float focus = 0.2f;

    [Range(0, 100)]
    public float nearScale = 50.0f;

    [Range(0, 100)]
    public float farScale = 20.0f;

    protected void Start() {
		CheckResources();
        cam = this.GetComponent<Camera>();
        cam.depthTextureMode |= cam.depthTextureMode;
	}

    void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (material != null) {

            int rtW = src.width/downSample;
            int rtH = src.height/downSample;

            RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH, 0);
            RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH, 0);

            Graphics.Blit(src, buffer0);

            for(int i=0; i< iterations; i++){
                material.SetVector("_BlurDir", new Vector4(1.0f, 0,0,0));

                Graphics.Blit(buffer0, buffer1, material, 0);

                material.SetVector("_BlurDir", new Vector4(0, 1.0f,0,0));

                RenderTexture.ReleaseTemporary(buffer0);
                Graphics.Blit(buffer1, buffer0, material, 0);

            }
            
            material.SetTexture("_Dof", buffer0);
            material.SetFloat("_Focus", focus);
            material.SetFloat("_NearScale", nearScale);
            material.SetFloat("_FarScale", farScale);

            Graphics.Blit(src, dest, material, 1);

            //Graphics.Blit(buffer0, dest);

            RenderTexture.ReleaseTemporary(buffer0);
        }
        else{
            Graphics.Blit(src, dest);
        }
    }

}
